<?php

namespace App\Http\Controllers\OpenShop\Feishu;

use App\Enums\BaseErrorCode;
use App\Enums\Check\CheckEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Controllers\BaseController;
use App\Http\Validate\OpenShop\InvestmentPromotion\SpaceDesignConfirmValidate;
use App\Http\Validate\OpenShop\InvestmentPromotion\SpaceDesignPreparationRefundValidate;
use App\Http\Validate\OpenShop\InvestmentPromotion\SpaceDesignSoftSendValidate;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignCostMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignSoftLogisticsModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Rules\Mobile;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\Feishu\ShopCheckAcceptService;
use App\Service\OpenShop\Feishu\ShopTagsService;
use App\Service\OpenShop\Feishu\SiteMissionService;
use App\Service\OpenShop\Feishu\SpaceDesignService;
use App\Service\OpenShop\OrderService;
use App\Service\Rms\ShopService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class SpaceDesignController extends BaseController
{

    /**
     * 筹备确认开店时间
     * @param Request $request
     * @param $orderNo
     * @return JsonResponse
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function preparationConfirmation(Request $request, $orderNo)
    {
        $this->validate($request, [
            'shopName'    => 'string',
            'phoneNumber' => new Mobile(),
        ]);
        $shopName = $request->post('shopName', '');
        $rmsInfo  = getRmsUserInfoByAuth();
        if (strpos($request->shopName, '的店') !== false) {
            return $this->fail(403, '门店名称不符合规范');
        }

        if (mb_strlen($shopName)) {
            //更改名店名称
            ShopService::updateShopName($orderNo, $shopName);
        }
        $actuallyParams = (object)[
            'orderNo'     => $orderNo,
            'managerId'   => $request->get('managerId'),
            'managerName' => $request->get('managerName'),
        ];

        ShopCheckAcceptService::onlyAssignManager(getRmsUserInfoByAuth(), $actuallyParams);
        // RMS 同步门店督导
        ShopService::updateShopCouncilorId($orderNo, $actuallyParams->managerId);
        // 刷新权限
        OrderService::updateOrderPermissionAnchor($orderNo);

        SpaceDesignService::preparationConfirm($orderNo, $rmsInfo->id, $rmsInfo->username, $request->receiverName,
            $request->phoneNumber, $request->regions, $request->addressDetail);

        return $this->success();
    }

    /**
     * 指派空间设计师
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function assignSpaceDesign(Request $request)
    {
        $this->validate($request, [
            'orderNo'    => 'required | string',
            'designUid'  => 'required | integer',
            'designName' => 'required | string',
        ]);
        $orderNo    = $request->orderNo;
        $designUid  = $request->designUid;
        $designName = $request->designName;
        $rmsInfo    = getRmsUserInfoByAuth();

        Config::set('event.connection', 'sync');

        SpaceDesignService::assignSpaceDesign($orderNo, $designUid, $designName, $rmsInfo->id);

        Config::set('event.connection', 'redis');

        // 自动生成设计师订单
        SpaceDesignService::insertSpaceDesignCostData(
            $orderNo,
            600000,
            150000,
            0,
            0,
            0
        );

        return $this->success();
    }

    /**
     * 上传空间设计图
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function uploadDesignMappingData(Request $request)
    {
        $this->validate($request, [
            'orderNo'          => 'required | string',
            'planeCad'         => 'required | string',
            'planePdf'         => 'required | string',
            'constructionCad'  => 'required | string',
            'constructionPdf'  => 'required | string',
            'effectImg'        => 'required | array',
            'equipments'       => 'required | array',
            'equipments.*.id'  => 'required|integer',
            'equipments.*.num' => 'required|integer',
//            'softOutfitXlsx'  => 'required | string',
//            'softOutfitFee'   => 'required | integer'
        ]);
        $orderNo         = $request->orderNo;
        $planeCad        = $request->planeCad;
        $planePdf        = $request->planePdf;
        $constructionCad = $request->constructionCad;
        $constructionPdf = $request->constructionPdf;
        $effectImg       = $request->effectImg;
//        $softOutfitXlsx  = $request->softOutfitXlsx;
//        $softOutfitFee   = $request->softOutfitFee;
        $equipments      = $request->equipments;
        SpaceDesignService::uploadDesignMappingData($orderNo, $planeCad, $planePdf, $constructionCad,
            $constructionPdf, $effectImg, $equipments);
        return $this->success();
    }

    /**
     * 修改设计图
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function setDesignMappingDataWithPower(Request $request, $orderNo)
    {
        return $this->setDesignMappingData($request, $orderNo);
    }

    /**
     * 修改设计图
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function setDesignMappingDataWithOutPower(Request $request, $orderNo)
    {
        return $this->setDesignMappingData($request, $orderNo);
    }

    /**
     * 修改设计图
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function setDesignMappingData(Request $request, $orderNo)
    {
        $this->validate($request, [
            'planeCad'        => 'required | string',
            'planePdf'        => 'required | string',
            'constructionCad' => 'required | string',
            'constructionPdf' => 'required | string',
            'effectImg'       => 'required | array',
            'softId'          => 'required|integer'
        ]);
        $planeCad        = $request->planeCad;
        $planePdf        = $request->planePdf;
        $constructionCad = $request->constructionCad;
        $constructionPdf = $request->constructionPdf;
        $effectImg       = $request->effectImg;
        $softOutfitXlsx  = $request->softOutfitXlsx;
        $softOutfitFee   = $request->softOutfitFee;
        $softId          = $request->softId;
        SpaceDesignService::setDesignMappingData($orderNo, $planeCad, $planePdf, $constructionCad, $constructionPdf,
            $effectImg, $softOutfitXlsx, $softOutfitFee, $softId);
        return $this->success();
    }

    /**
     * 设计师确认设计模块
     * @param Request $request
     * @return JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function confirmSpaceDesign(Request $request)
    {
        $params = SpaceDesignConfirmValidate::insertValidate($request->all());
        SpaceDesignService::insertSpaceDesignCostData(
            $params['orderNo'],
            $params['designFee'],
            $params['merchantFee'],
            $params['storeArea'],
            $params['designArea']
        );
        return $this->success();
    }

    /**
     * 添加设计订单
     * @param Request $request
     * @param $orderNo
     * @return JsonResponse
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function addCostOrder(Request $request)
    {
        $this->validate($request, [
            'orderNo'        => 'required|string',
            'overDesignArea' => 'required|integer',
        ]);
        $orderNo        = $request->orderNo;
        $overDesignArea = $request->overDesignArea;
        $designFee      = (int)$request->designFee ?? 0;
        $merchantFee    = (int)$request->merchantFee ?? 0;
        $rmsInfo        = getRmsUserInfoByAuth();
        SpaceDesignService::addCostOrder($orderNo, $overDesignArea, $designFee, $merchantFee, $rmsInfo->id);
        return $this->success();
    }

    /**
     * @return JsonResponse
     * @throws Exception
     */
    public function addCostOrderForm(Request $request): JsonResponse
    {
        $orderNo   = $request->orderNo;
        $orderSign = OpenShopSiteLocationModel::query()->whereIn('source',
            [
                OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                OpenShopSiteLocationModel::SOURCE_HOUSING
            ])->where('orderNo', $orderNo)->first();
        return $this->success(SpaceDesignService::addCostOrderForm($orderSign->cityCode));
    }

    /**
     * 添加软装订单
     * @param Request $request
     * @return JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function addSoftOrder(Request $request)
    {
        $this->validate($request, [
            'orderNo'        => 'required | string',
//            'softOutfitXlsx' => 'required | string',
//            'softOutfitFee'  => 'required | integer'
            'equipments'       => 'required | array',
            'equipments.*.id'  => 'required|integer',
            'equipments.*.num' => 'required|integer',
            'equipments.*.non_standard_unit_num' => 'numeric',
            'equipments.*.non_standard_remark'   => 'string',
        ]);
        $rmsInfo        = getRmsUserInfoByAuth();
        $orderNo        = $request->orderNo;
//        $softOutfitXlsx = $request->softOutfitXlsx;
//        $softOutfitFee  = $request->softOutfitFee;
        SpaceDesignService::addSoftOrder($orderNo, $rmsInfo, $request->equipments);
        return $this->success();
    }

    /**
     * 获取设计订单详情
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function costOrderInfo(Request $request, $preparationNo)
    {
        $orderInfo = SpaceDesignService::getCostOrderInfo($preparationNo);
        return $this->success($orderInfo);
    }

    /**
     * 获取软装订单详情
     * @param Request $request
     * @param $preparationNo
     * @return JsonResponse
     */
    public function softOrderInfo(Request $request, $preparationNo)
    {
        $orderInfo = SpaceDesignService::getSoftOrderInfo($preparationNo);
        return $this->success($orderInfo);
    }

    /**
     * 关闭设计订单
     *
     * @param $preparationNo
     * @return JsonResponse
     * @throws Exception
     */
    public function closeCostOrder($preparationNo): JsonResponse
    {
        SpaceDesignService::closeCostOrder($preparationNo);
        return $this->success();
    }

    /**
     * 关闭软装订单
     *
     * @param string $preparationNo
     * @return JsonResponse
     * @throws Exception
     */
    public function closeSoftOrder(string $preparationNo): JsonResponse
    {
        SpaceDesignService::closeSoftOrder($preparationNo);
        return $this->success();
    }

    /**
     * 关闭设备订单
     * @param Request $request
     * @return JsonResponse
     */
    public function closeEquipmentOrder(Request $request)
    {
        $id      = $request->post('id');
        $orderNo = $request->post('orderNo');
        $sysType = $request->post('sysType', CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT);

        $this->validate($request, [
            'id'      => 'required|integer',
            'orderNo' => 'required|string',
            'sysType' => 'required|integer|in:' . CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT . ',' . CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE
        ]);

        $shopId = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->value('shopId');

        $body = OrmNewOrderRemote::cancelNewOrder($id, getRmsUserInfoByAuth()->username ?? '');

        $code = $body['code'] ?? null;
        if ($code) {
            return $this->fail(500, $body['msg'] ?? '订货系统走丢了');
        }

        // 校验是否有待支付订单
        $lists = OrmNewOrderRemote::myEquipments($shopId, $sysType)['data']['list'] ?? [];

        $waitPay = false;
        foreach ($lists as $order) {
            $status = $order['status'] ?? 0;
            if (in_array($status,
                [OrmNewOrderRemote::NEW_ORDER_STATUS_WAIT, OrmNewOrderRemote::NEW_ORDER_STATUS_PART])) {
                $waitPay = true;
            }
        }

        // 关闭待支付任务
        if (!$waitPay) {

            if ($sysType == CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT) {
                $stepStatus = MissionTemplateEnum::STEP_STATUS_16;
            } else if ($sysType == CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE) {
                $stepStatus = MissionTemplateEnum::STEP_STATUS_17;
            } else {
                $stepStatus = 0;
            }

            // 关闭任务
            SiteMissionService::closePayCloseMission($orderNo, $stepStatus);
//            (new ShopTagsService($softInfo->orderNo))->updateSoftPayTag();
        }

        return $this->success();
    }

    /**
     * 完成软装订单
     * @param Request $request
     * @param $preparationNo
     * @return JsonResponse
     */
    public function completeSoftOrder(Request $request, $preparationNo)
    {
        SpaceDesignService::completeSoftOrder($preparationNo);
        return $this->success();
    }

    /**
     * 完成设计订单
     * @param Request $request
     * @param $preparationNo
     * @return JsonResponse
     */
    public function completeCostOrder(Request $request, $preparationNo)
    {
        SpaceDesignService::completeCostOrder($preparationNo);
        return $this->success();
    }

    /**
     * 筹备订单退款
     * @param Request $request
     * @return JsonResponse
     */
    public function refundPreparationOrder(Request $request)
    {
        $params = SpaceDesignPreparationRefundValidate::refundValidate($request->all());
        $remark = $params['remark'] ?? '';
        SpaceDesignService::refundPreparationOrder($params['preparationNo'], $params['type'], $params['refundMoney'],
            $remark);
        return $this->success();
    }

    /**
     * 软装发货
     * @param Request $request
     * @return JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function softFitSendOut(Request $request)
    {
        $params  = SpaceDesignSoftSendValidate::insertValidate($request->all());
        $rmsInfo = getRmsUserInfoByAuth();
        SpaceDesignService::softSendProduct($params, $rmsInfo);
        return $this->success();
    }

    /**
     * 软装发货列表
     * @param Request $request
     * @param $preparationNo
     * @return JsonResponse
     */
    public function getSoftSendList(Request $request, $preparationNo)
    {
        $softSendList = SpaceDesignService::getSoftSendList($preparationNo);
        return $this->success($softSendList);
    }

    public function deleteSoftSendInfo(Request $request, $sendNo)
    {
        $rmsInfo = getRmsUserInfoByAuth();
        SpaceDesignService::deleteSoftSendInfo($sendNo, $rmsInfo);
        return $this->success();
    }

    /**
     * 快递公司列表
     * @return JsonResponse
     * @throws Exception
     */
    public function getExpressList()
    {
        $configInfo = ConfigService::config('openShop', 'express');
        return $this->success($configInfo['express'] ?? []);
    }

    /**
     * 商家app物流接口
     * @param Request $request
     * @param $orderNo
     * @return JsonResponse
     */
    public function getSoftSendListByOrderNo(Request $request, $orderNo)
    {
        $softSendList = SpaceDesignService::getSoftSendListByOrderNo($orderNo);
        return $this->success($softSendList);
    }

    /**
     * 内部调整设计单金额
     * @param Request $request
     * @param string $orderNo
     * @return void
     */
    public function saveDebugDesignPrice(Request $request, string $orderNo): JsonResponse
    {
        $preparationNo = SpaceDesignService::saveDebugDesignPrice($orderNo);

        return $this->success(['preparationNo' => $preparationNo]);
    }

    /**
     * 跳步骤
     * @param Request $request
     * @param string $orderNo
     * @return JsonResponse
     */
    public function skipStep(Request $request, string $orderNo): JsonResponse
    {
        $stepStatus = $request->post('stepStatus');
        $remark     = $request->post('remark');

        $request->merge(['orderNo' => $orderNo]);

        $this->validate($request, [
            'orderNo'    => 'required|string',
            'remark'     => 'required|string',
            'stepStatus' => ['required', 'integer', Rule::in([MissionTemplateEnum::STEP_STATUS_15, MissionTemplateEnum::STEP_STATUS_8, MissionTemplateEnum::STEP_STATUS_9])],
        ]);

        $user = getRmsUserInfoByAuth();

        SpaceDesignService::skipStep($orderNo, $stepStatus, $remark, $user);

        return $this->success();
    }
}
